<template>
  <div class="loginbox">

    <van-form @submit="onSubmit" @failed="onFail">
      <!-- 手机号 -->
      <van-field
        autocomplete="off"
        v-model="form.phone"
        name="phone"
        label="手机号"
        placeholder="请输入手机号"
        left-icon="phone-o"
        clearable
        :rules="[
            { required: true, message: '请输入手机号' },
            { pattern: reg.phone, message: '请输入正确的手机号' }
        ]"
      />

      <!-- 验证码  使用value值 必须绑定name="captcha" 否则响应失败-->
      <van-field
        v-model="form.captcha"
        name="captcha"
        center
        clearable
        left-icon="qr"
        label="验证码"
        placeholder="请输入验证码"
        :rules="[
            { required: true, message: '请输入验证码' },
            { pattern: reg.code, message: '验证码错误' } // 该验证码为4为数字组成
        ]"
      >
        <template #button>
          <!-- 有手机号才能发送验证码，否则验证码不能点击发送 -->
            <van-button v-if="flag" size="small" :disabled="disabled" type="primary" @click.stop.prevent="sendCaptcha">发送验证码</van-button>
            <van-button v-else size="small" disabled  > {{count}} S</van-button>
        </template>
      </van-field>

      <div style="margin: 16px;display:flex;" class="jcsb"  >
          <p>
              <router-link :to="{name:'register'}" class="link1 mb10">还未注册,去注册?</router-link>
          </p>
          <p>
              <router-link :to="{name:'forgetpassword'}" class="link1 mb10">忘记密码?</router-link>
          </p>
      </div>

      <div style="margin: 16px;">
          <van-button  block type="primary" native-type="submit">登录</van-button>
      </div>

    </van-form>
  </div>
</template>

<script>

var timer = null

export default {
  data() {
    return {
      form: {},
      type: 'password',
      flag: true,
      count: 60
    }
  },
  mounted() {
    this.form  = {
      phone: this.$route.query.phone ? this.$route.query.phone : localStorage.getItem('phone')
    }
  },
  computed: {
    disabled() {
      return !this.reg.phone.test(this.form.phone)
    }
  },
  destroyed() { // 离开销毁计数器
    clearInterval(timer)
    timer = null
  },
  methods: {
    async send() {
      let res = await this.$ajax.sendCaptcha({
        phone: this.form.phone 
      })
      const { code } = res
      if(code == 200){
        this.showSuccessMsg("验证码发送成功!")
      } else {
        this.showErrorMsg("验证码发送失败,今日次数已经用完!")
      }
    },
    sendCaptcha() { // 获取验证码
    this.send()

    this.flag =false
    this.count--
    timer = setInterval(() => {
      if(this.count > 0){
        this.count--
        this.flag = false
      } else {
        clearInterval(timer)
        timer = null
        this.count = 60
        this.flag = true 
      }
    }, 1000)
  },
    onSubmit(value) {
      // 登录操作 get 
      // 先判断手机号是否已经被注册
      // 被注册才能校验 
      // 没有注册提示用户去注册

      this.$ajax.findUser({
        phone: value.phone
      })
      .then(res => {
        if(res.length > 0){
          // this.$ajax.verifyCaptcha(this.form) // 方法一
          this.$ajax.verifyCaptcha(value) // 方法二：使用value值 必须绑定name="captcha" 否则响应失败
          .then(result => {
             const { code } = result
             if(code == 200){
               this.showSuccessMsg("校验成功")
              
               //  this.$router.push({ name: 'mine' })
               if(from.name == 'register' || from.name == 'forgetpassword' || from.name == 'changepassword') {
                   localStorage.setItem('fromwhere', 'mine')
               } else {
                   localStorage.setItem('fromwhere', '-1')
               }

               localStorage.setItem('phone', value.phone)
               //  登录成功就存储userInfo
              this.changeUserInfo(res[0])
             } else {
               this.showErrorMsg("校验失败,请重新登录")
             }
          })
        } else {
          this.showErrorMsg("手机号未注册,请先注册")
        }
      })
    },
    onFail(){
      this.$toast.fail('请输入有效的登录信息')
    },
    changeType() {
      this.type = this.type == 'password' ? 'type' : 'password'
    },
  }
}
</script>

<style lang="scss" scoped>


</style>